package com.aipartner.service.impl;

import com.aipartner.common.Result;
import com.aipartner.dto.LoginResponse;
import com.aipartner.dto.UserInfoResponse;
import com.aipartner.dto.WechatLoginRequest;
import com.aipartner.entity.User;
import com.aipartner.mapper.UserMapper;
import com.aipartner.service.UserService;
import com.aipartner.util.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.reactive.function.client.WebClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;


/**
 * User Service Implementation
 * 
 * @author AI Partner Team
 * @since 2024-01-20
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    
    private final UserMapper userMapper;
    private final JwtUtil jwtUtil;
    private final WebClient webClient;
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    @Transactional
    public Result<LoginResponse> wechatLogin(WechatLoginRequest request) {
        try {
            // Simulate WeChat openid retrieval (in real implementation, call WeChat API)
            String openid = simulateGetOpenId(request.getCode());
            if (openid == null) {
                return Result.fail("Invalid authorization code");
            }
            
            // Check if user exists
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            // 字段名与表结构对齐：open_id
            queryWrapper.eq("open_id", openid);
            User existingUser = userMapper.selectOne(queryWrapper);
            
            // Parse user info from WeChat
            String nickname = "微信用户";
            String avatarUrl = "";
            
            if (request.getUserInfo() != null && !request.getUserInfo().trim().isEmpty()) {
                try {
                    JsonNode userInfoNode = objectMapper.readTree(request.getUserInfo());
                    if (userInfoNode.has("nickName")) {
                        nickname = userInfoNode.get("nickName").asText("微信用户");
                    }
                    if (userInfoNode.has("avatarUrl")) {
                        avatarUrl = userInfoNode.get("avatarUrl").asText("");
                    }
                } catch (Exception e) {
                    log.warn("Failed to parse user info: {}", e.getMessage());
                }
            }
            
            User user;
            if (existingUser != null) {
                // Update existing user info
                user = existingUser;
                user.setNickname(nickname);
                user.setAvatarUrl(avatarUrl);
                userMapper.updateById(user);
            } else {
                // Create new user
                user = new User();
                user.setOpenid(openid);
                user.setNickname(nickname);
                user.setAvatarUrl(avatarUrl);
                user.setVipLevel(0);
                userMapper.insert(user);
            }
            
            // Generate JWT token
            String token = jwtUtil.generateToken(user.getId().toString(), user.getNickname());
            if (token == null) {
                return Result.fail("Failed to generate token");
            }
            
            // Create login response
            LoginResponse response = new LoginResponse();
            response.setToken(token);
            // Set other fields based on actual LoginResponse structure
            
            return Result.success(response);
        } catch (Exception e) {
            log.error("WeChat login failed: {}", e.getMessage(), e);
            return Result.fail("Login failed, please try again");
        }
    }
    
    @Override
    public Result<UserInfoResponse> getUserInfo(Long userId) {
        try {
            User user = userMapper.selectById(userId);
            if (user == null) {
                return Result.fail("User not found");
            }
            
            UserInfoResponse response = new UserInfoResponse();
            BeanUtils.copyProperties(user, response);
            
            return Result.success(response);
        } catch (Exception e) {
            log.error("Get user info failed: {}", e.getMessage(), e);
            return Result.fail("Failed to get user information");
        }
    }
    
    @Override
    @Transactional
    public Result<String> updateUserInfo(Long userId, UserInfoResponse request) {
        try {
            User user = userMapper.selectById(userId);
            if (user == null) {
                return Result.fail("User not found");
            }
            
            // Update user information
            user.setNickname(request.getNickname());
            user.setAvatarUrl(request.getAvatarUrl());
            // Update other fields based on actual User entity structure
            
            userMapper.updateById(user);
            
            return Result.success("User information updated successfully");
        } catch (Exception e) {
            log.error("Update user info failed: {}", e.getMessage(), e);
            return Result.fail("Failed to update user information");
        }
    }
    
    @Override
    public User getUserByOpenId(String openId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openId);
        return userMapper.selectOne(queryWrapper);
    }
    
    @Override
    public User createUser(User user) {
        userMapper.insert(user);
        return user;
    }
    
    @Override
    public User updateUser(User user) {
        userMapper.updateById(user);
        return user;
    }
    
    @Override
    public boolean increaseAiCalls(Long userId) {
        // Mock implementation - replace with actual logic
        log.info("Increasing AI calls for user: {}", userId);
        return true;
    }
    
    @Override
    public boolean canCallAi(Long userId) {
        // Mock implementation - replace with actual logic
        return true;
    }
    
    @Override
    public boolean updateBalance(Long userId, java.math.BigDecimal amount) {
        // Mock implementation - replace with actual logic
        log.info("Updating balance for user {}: {}", userId, amount);
        return true;
    }
    
    @Override
    public boolean updateVipInfo(Long userId, Integer vipLevel, java.time.LocalDateTime expireTime) {
        // Mock implementation - replace with actual logic
        log.info("Updating VIP info for user {}: level={}, expireTime={}", userId, vipLevel, expireTime);
        return true;
    }
    
    @Override
    public void resetDailyAiCalls() {
        // Mock implementation - replace with actual logic
        log.info("Resetting daily AI calls for all users");
    }
    
    // ==================== 管理端相关方法 ====================
    
    @Override
    public Page<User> getAdminUserList(Page<User> page, String userId, String nickname, String vipStatus) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        
        // 用户ID筛选
        if (userId != null && !userId.trim().isEmpty()) {
            try {
                wrapper.eq(User::getId, Long.valueOf(userId.trim()));
            } catch (NumberFormatException e) {
                // 如果ID格式不正确，返回空结果
                return new Page<>(page.getCurrent(), page.getSize());
            }
        }
        
        // 昵称筛选
        if (nickname != null && !nickname.trim().isEmpty()) {
            wrapper.like(User::getNickname, nickname.trim());
        }
        
        // VIP状态筛选
        if (vipStatus != null && !vipStatus.trim().isEmpty()) {
            if ("1".equals(vipStatus)) {
                wrapper.gt(User::getVipLevel, 0);
            } else if ("0".equals(vipStatus)) {
                wrapper.eq(User::getVipLevel, 0);
            }
        }
        
        // 排序：最新注册的在前
        wrapper.orderByDesc(User::getCreateTime);
        
        return userMapper.selectPage(page, wrapper);
    }
    
    @Override
    public User getById(Long userId) {
        return userMapper.selectById(userId);
    }
    
    /**
     * Simulate getting OpenID from WeChat (replace with actual WeChat API call)
     */
    private String simulateGetOpenId(String code) {
        // In real implementation, call WeChat API:
        // GET https://api.weixin.qq.com/sns/jscode2session
        // Parameters: appid, secret, js_code, grant_type
        
        // For demo purposes, return a simulated openid
        return "simulated_openid_" + System.currentTimeMillis();
    }
}